package org.jsola.contract.service.impl;

import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.dao.ITemplateVariableDAO;
import org.jsola.contract.dto.TemplateVariableAddDTO;
import org.jsola.contract.dto.TemplateVariableUpdateDTO;
import org.jsola.contract.entity.TemplateVariableDO;
import org.jsola.contract.query.TemplateVariableQuery;
import org.jsola.contract.service.ITemplateVariableService;
import org.jsola.contract.vo.TemplateVariableListVO;
import org.jsola.contract.vo.TemplateVariableVO;
import org.jsola.core.Page;
import org.jsola.orm.filter.Order;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.mapperhelper.EntityHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同模板关联变量
 *
 * @author JanusMix
 */
@Service("contractTemplateVariableServiceImpl")
public class TemplateVariableServiceImpl implements ITemplateVariableService {

    @Autowired
    private ITemplateVariableDAO templateVariableDAO;

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public TemplateVariableVO save(TemplateVariableAddDTO templateVariableAddDTO, TokenUser tokenUser) {
        // 转DO
        TemplateVariableDO templateVariableDO = templateVariableAddDTO.to(TemplateVariableDO.class);
        if (templateVariableAddDTO.getTemplateId() != null) {
            //先删除所有现有的
            List<TemplateVariableDO> list = this.selectByTemplateId(templateVariableAddDTO.getTemplateId(), tokenUser.getSiteId());
            this.deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), list.stream().map(TemplateVariableDO::getId).toArray());
        }
        // 保存
        templateVariableDO = save(templateVariableDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return templateVariableDO.to(TemplateVariableVO.class);
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public List<TemplateVariableVO> batchSave(List<TemplateVariableAddDTO> templateVariableAddDTOList, TokenUser tokenUser) {
        if (CollectionUtils.isEmpty(templateVariableAddDTOList)) {
            return null;
        }
        //先删除所有现有的
        Long templateId = templateVariableAddDTOList.get(0).getTemplateId();
        List<TemplateVariableDO> list = this.selectByTemplateId(templateId, tokenUser.getSiteId());
        this.deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), list.stream().map(TemplateVariableDO::getId).toArray());

        List<TemplateVariableDO> templateVariableDOList = templateVariableAddDTOList
                .parallelStream()
                .map(templateVariableAddDTO -> {
                    TemplateVariableDO templateVariableDO = templateVariableAddDTO.to(TemplateVariableDO.class);
                    templateVariableDO.preInsert(tokenUser.getUserId());
                    templateVariableDO.setSiteId(tokenUser.getSiteId());
                    return templateVariableDO;
                }).collect(Collectors.toList());
        templateVariableDAO.insertListAndSetId(templateVariableDOList);
        return templateVariableDOList
                .parallelStream()
                .map(templateVariableDO -> templateVariableDO.to(TemplateVariableVO.class))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public int update(TemplateVariableUpdateDTO templateVariableUpdateDTO, TokenUser tokenUser) {
        //转DO
        TemplateVariableDO templateVariableDO = templateVariableUpdateDTO.to(TemplateVariableDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(templateVariableDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = ContractConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, Long... templateVariableIds) {
        return deleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) templateVariableIds);
    }


    @Override
    public TemplateVariableVO selectById(Long templateVariableId, String siteId) {
        TemplateVariableDO templateVariableDO = selectDOById(templateVariableId, siteId);
        if (templateVariableDO == null) {
            return null;
        }
        return templateVariableDO.to(TemplateVariableVO.class);
    }

    @Override
    public List<TemplateVariableListVO> select(TemplateVariableQuery templateVariableQuery, String siteId) {
        List<TemplateVariableDO> templateVariableDOList = selectDO(templateVariableQuery, siteId);
        if (CollectionUtils.isEmpty(templateVariableDOList)) {
            return templateVariableDOList == null ? null : new ArrayList<>();
        }
        return templateVariableDOList.stream()
                .map(templateVariableDO -> templateVariableDO.to(TemplateVariableListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(TemplateVariableQuery templateVariableQuery, String siteId) {
        return templateVariableDAO.findCountByQuery(templateVariableQuery, siteId);
    }

    @Override
    public Page<TemplateVariableListVO> selectPage(TemplateVariableQuery templateVariableQuery, String siteId) {
        //将order参数中的propertyName改为dbName
        List<Order> orders = templateVariableQuery.getOrders();
        if (!CollectionUtils.isEmpty(orders)) {
            orders.forEach(order ->
                    order.setProperty(EntityHelper.getEntityTable(TemplateVariableDO.class).getPropertyMap().get(order.getProperty()).getColumn())
            );
        }
        templateVariableQuery.setOrders(orders);
        Page<TemplateVariableDO> page = templateVariableDAO.findPageByQuery(templateVariableQuery, siteId);
        return page.to(TemplateVariableListVO.class);
    }

    @Override
    public TemplateVariableDO selectDOById(Long templateVariableId, String siteId) {
        return templateVariableDAO.findById(templateVariableId, siteId);
    }

    @Override
    public List<TemplateVariableDO> selectDO(TemplateVariableQuery templateVariableQuery, String siteId) {
        //将order参数中的propertyName改为dbName
        List<Order> orders = templateVariableQuery.getOrders();
        if (!CollectionUtils.isEmpty(orders)) {
            orders.forEach(order ->
                    order.setProperty(EntityHelper.getEntityTable(TemplateVariableDO.class).getPropertyMap().get(order.getProperty()).getColumn())
            );
        }
        templateVariableQuery.setOrders(orders);
        return templateVariableDAO.findListByQuery(templateVariableQuery, siteId);
    }

    @Override
    public List<TemplateVariableDO> selectByTemplateId(Long templateId, String siteId) {
        Example example = new Example(TemplateVariableDO.class);
        example.and()
                .andEqualTo("siteId", siteId)
                .andEqualTo("templateId", templateId);
        return this.templateVariableDAO.selectByExample(example);
    }

    @Override
    public List<TemplateVariableDO> selectByTemplateIds(List<Long> templateIds, String siteId) {
        if (CollectionUtils.isEmpty(templateIds)) {
            return new ArrayList<>();
        }
        Example example = new Example(TemplateVariableDO.class);
        example.and()
                .andEqualTo("siteId", siteId)
                .andIn("templateId", templateIds);
        return templateVariableDAO.selectByExample(example);
    }


}




